package forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @projectName: JUC
 * @package: forkjoin
 * @className: forkjoinDemo
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/3/4 0:47
 * @version: 1.0
 */
public class forkjoinDemo extends RecursiveTask<Long> {
    /* 解决方案 也是有三六九等的，比如案例 求和
     * 最低等 就是直接for循环求和
     * 中等 使用forkjion
     * 高等 stream 并行流
     * */
//开始
    private long start;
    //结束
    private long end;
    //到多少值,才开始分开任务
    private long threshold = 10000L;

    public forkjoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        //判断超过阈值的时候 开始使用 fork join
        if (end - start > threshold) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            //    求出中间值
            long mid = (start - end) / 2;
            forkjoinDemo task1 = new forkjoinDemo(start, mid);

            //拆分任务，把任务压入线程队列
            task1.fork();
            forkjoinDemo task2 = new forkjoinDemo(mid + 1, end);
            task2.fork();
            return task1.join() + task2.join();
        }
    }
}
